﻿/*
 * process.cpp
 *
 *  Created on: 2018年5月16日
 *      Author: Dylan.Gao
 */

#include <dm/export.hpp>

#define DM_API_OS_SYS DM_API_EXPORT

#include <dm/os/sys/process.hpp>

#include <cstdio>
#include <signal.h>

#ifdef WIN32
#include <direct.h>
#else
#include <dirent.h>
#endif

namespace dm{
namespace os{
namespace sys{

/**
 * 判断进程是否有效
 * @param process
 * @return
 */
bool ifProcess( process_t process ){
	// 判断进程是否存在
	if( process<0 )
		return false;
#ifdef WIN32
	HANDLE ph = OpenProcess(SYNCHRONIZE, FALSE, process);
	if (ph) {
		CloseHandle(ph);
		return true;
	}
	else {
		return false;
	}
#else
	char dirpath[128];
	std::sprintf(dirpath,"/proc/%d",process);

	DIR* dirp = opendir(dirpath);
	if( dirp ){
		closedir(dirp);
		return true;
	}else
		return false;
#endif
}

void killProcess( process_t process ){
#ifdef WIN32
	HANDLE ph = OpenProcess(SYNCHRONIZE, FALSE, process);
	if (ph) {
		TerminateProcess(ph, 0);
		CloseHandle(ph);
	}
#else
	killProcess(process,SIGKILL);
#endif
}

void killProcess( process_t process,int sig ){
	if( process<=0 )
		return;
#ifndef WIN32
	kill(process,sig);
#endif
}

}
}
}

